//
//  Pet_StoryViewController.swift
//  PetApp
//
//  Created by mac on 2023/9/20.
//  Copyright © 2023 Pet_. All rights reserved.
//

import UIKit

class Pet_StoryViewController: BasicViewController {

    private lazy var itemsTableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.register(StoryCell.self, forCellReuseIdentifier: StoryCell.description())
        view.rowHeight = UITableView.automaticDimension
        return view
    }()
    let addB = UIButton.initV(img: "icon_post")
    var dataSource:[InfoUtil.room]? = []
    let topI = UIImageView.initImgView(img: "oetStory")

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getdata()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "Pet Story"
        view.subviews {
            topI
            itemsTableView
            addB
        }
        topI.left(15.Fit).right(15.Fit).height(170.Fit).top(NavHeight + 15.Fit)
        
        itemsTableView.left(0).right(0).bottom(0)
        itemsTableView.Top == topI.Bottom + 40.Fit
        
        addB.size(50.Fit).right(50.Fit).bottom(50.Fit)
        addB.addAct {
            let vc = Pet_PublishStoryViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        itemsTableView.emptyGameView(.noList)
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name("BlockRefreshNotice"), object: nil, queue: nil) {[weak self] noti in
            self?.getdata()
        }
        
    }
    
    func getdata() -> Void {
        Toast_View_Tool.show()
        RT.getRoomList { list in
            Toast_View_Tool.dismiss()
            self.dataSource?.removeAll()
            for item in list.lists{
                if item.info3 == "1" {
                    self.dataSource?.append(item)
                }
            }
            self.itemsTableView.reloadData()
        }
    }
}

extension Pet_StoryViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: StoryCell.description(), for: indexPath) as! StoryCell
        cell.model = dataSource?[indexPath.row]
        cell.vc = self
        return cell
    }
        
}


class StoryCell: UITableViewCell {
    
    var vc:Pet_StoryViewController?
    let backV = UIView.init(frame: .zero)
    let avarB = UIButton.initV(img: "avarB")
    let nameL = UILabel.initV(UIFont.setTypeFace(16,type: .medium), text: "", textColor: .color(hexString: "#666666"))
    let timeL = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "", textColor: .color(hexString: "#999999"))
    let descL = UILabel.initV(UIFont.setTypeFace(16,type: .medium), text: "", textColor: .color(hexString: "#333333"))
    let moreB = UIButton.initV(img: "icon_more 2")
    let giftB = UIButton.initV(img: "gitticobn")
    private lazy var followB: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(14.Fit,type: .medium)
        button.setTitleColor(mainColor, for: .normal)
        button.setTitle("Follow", for: .normal)
        button.backgroundColor = .black
        return button
    }()
    let commentB = UIButton.initV(text: "", img: "")
    
    
    var model:InfoUtil.room?{
        didSet{
            self.nameL.text = model?.info
            self.timeL.text = model?.info4
            if let url = URL(string: self.model?.icon ?? "") {
                self.avarB.kf.setImage(with: url, for: .normal,placeholder: .init(named: "avarB"))
            }
            self.descL.text = model?.info0
            self.giftB.setTitle(model?.data1, for: .normal)
            
            if let str = self.model?.info5,str.count != 0 {
                let arr = str.components(separatedBy: "@@")
                self.commentB.setTitle("\(arr.count) Comment", for: .normal)
            }else{
                self.commentB.setTitle("0 Comment", for: .normal)
            }

            RT.careFriendState(idstring: self.model?.createUserId ?? "") { s in
                self.followB.isSelected = s == "1"
                self.followB.setTitle(s == "1" ? "Unfollow" : "Follow", for: .normal)
                self.followB.backgroundColor = s == "1" ? UIColor.gray : .black
                self.followB.setTitleColor(s == "1" ? UIColor.color(hexString: "#999999") : mainColor, for: .normal)
            }

        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            backV.subviews {
                avarB
                moreB
                nameL
                timeL
                descL
                giftB
                followB
                commentB
            }
        }
        
        backV.right(15.Fit).left(15.Fit).bottom(10.Fit).top(0)
        backV.backgroundColor = .white
        backV.setAllCorners(corner: 10.Fit)
        
        avarB.size(40.Fit).left(15.Fit).top(15.Fit)
        avarB.setAllCorners(corner: 20.Fit)
        avarB.addAct {
            guard self.model?.createUserId != USEINFOMODEL.id else {
                return
            }
            let vc = Pet_UserinfoViewController()
            vc.userID = self.model?.createUserId
            UIApplication.topViewController()?.navigationController?.pushViewController(vc, animated: true)
        }
        
        moreB.size(40.Fit).right(20.Fit)
        moreB.CenterY == avarB.CenterY
        moreB.addAct {
            let page = Edit_Choose_Photo_Interface(type: .reportAndBlock(userId: self.model?.createUserId?.intValue ?? 0,personal: false))
            UIApplication.topViewController()?.present(page, animated: true)
        }
        
        nameL.height(20.Fit).top(15.Fit).width(80.Fit)
        nameL.Leading == avarB.Trailing + 15.Fit
        
        timeL.height(20.Fit).width(80.Fit)
        timeL.Leading == avarB.Trailing + 15.Fit
        timeL.Top == nameL.Bottom

        descL.right(15.Fit).left(15.Fit).bottom(85.Fit)
        descL.Top == avarB.Bottom + 5.Fit
        descL.numberOfLines = 0
        
        giftB.left(20.Fit).bottom(25.Fit).height(35.Fit).width(60.Fit)
        giftB.contentHorizontalAlignment = .leading
        giftB.setTitle("0", for: .normal)
        giftB.setTitleColor(.color(hexString: "#BE9146"), for: .normal)
        giftB.titleLabel?.font = .systemFont(ofSize: 14)
        giftB.addAct {
            let view = GiftSend_View()
            view.sendBlock = {
                RT.buyGiftWith(cost: "20") { info in
                    Toast_View_Tool.show(type: .success,text: "Send Success!")
                    var model1 = self.model!
                    model1.data1 = "\(model1.data1!.intValue + 1)"
                    RT.updateHouse(paraInfo: (model1.toJSON())!) { info in
                        self.vc?.getdata()
                    }
                }
            }
            let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth, height: screenHeight)))
            page.isCloseFromClean = false
            page.animatedPop()
        }
        
        commentB.right(40.Fit).height(40.Fit)
        commentB.CenterY == giftB.CenterY
        commentB.Leading == giftB.Trailing + 30.Fit
        
        commentB.titleLabel?.font = .setTypeFace(14.Fit,type: .medium)
        commentB.backgroundColor = .color(hexString: "#F8E2BC")
        commentB.setAllCorners(corner: 20.Fit)
        commentB.setTitleColor(.color(hexString: "#BE9146"), for: .normal)
        commentB.addAct {
            let view = commentView()
            view.model = self.model
            view.doneB = {
                self.vc?.getdata()
            }
            view.modalPresentationStyle = .overFullScreen
            self.vc?.present(view, animated: false)
        }
        
        followB.width(80.Fit).height(30).top(15.Fit)
        followB.Leading == timeL.Trailing + 15.Fit
        followB.setAllCorners(corner: 15.Fit)
        followB.addAct {
            guard self.model?.createUserId != USEINFOMODEL.id else {
                Toast_View_Tool.show(type: .error,text: "You can't follow yourself")
                return
            }
            Toast_View_Tool.show()
            let type = self.followB.isSelected == true ? "0" : "1"
            RT.AddDeleteFriend(idstring: self.model?.createUserId ?? "", type: type) { s in
                self.followB.isSelected = !self.followB.isSelected
                Toast_View_Tool.dismiss()
                self.vc?.getdata()
            }
        }
            
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
